package com.hpe.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpe.dao.CourseMapper;
import com.hpe.dao.QuestionsMapper;
import com.hpe.pojo.BigQuestion;
import com.hpe.pojo.Course;
import com.hpe.pojo.Questions;
import com.hpe.service.QuestionService;
import com.hpe.util.DownloadUtil;
import com.hpe.util.ExcelUtil;
import com.hpe.util.ServerResponse;
import com.hpe.vo.QuestionVo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:TangWenhao
 * @Description:
 * @Date:19:04 2017/9/25
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private CourseMapper courseMapper;


    @Override
    public void insert(Questions q) {

    }

    @Override
    public void delete(int id) {

    }

    @Override
    public void update(Questions q) {

    }

    @Override
    public void insert(BigQuestion bigQue) {

    }

    @Override
    public List<Questions> findByIds(String[] ids) {
        //String idss=ToolUtil.arraytoString(ids);
        List<Questions> list = new ArrayList<>();
        for (String id : ids) {
            if (id.equals("")) {
                continue;
            }
            //去除富文本编辑器添加的段首与段尾的<p>标签
            Questions questions = questionsMapper.selectByPrimaryKey(Integer.valueOf(id));
            int index = questions.getQuetitle().indexOf("<p>");
            if (index == 0) {
                questions.setQuetitle(questions.getQuetitle().substring(3, questions.getQuetitle().length() - 4));
            }
            int index1 = questions.getChoiced().indexOf("<p>");
            if (index1 == 0) {
                questions.setChoiced(questions.getChoiced().substring(3, questions.getChoiced().length() - 4));
            }
            int index2 = questions.getChoicec().indexOf("<p>");
            if (index2 == 0) {
                questions.setChoicec(questions.getChoicec().substring(3, questions.getChoicec().length() - 4));
            }
            int index3 = questions.getChoiceb().indexOf("<p>");
            if (index3 == 0) {
                questions.setChoiceb(questions.getChoiceb().substring(3, questions.getChoiceb().length() - 4));
            }
            int index4 = questions.getChoicea().indexOf("<p>");
            if (index4 == 0) {
                questions.setChoicea(questions.getChoicea().substring(3, questions.getChoicea().length() - 4));
            }
            //HtmlUtils重新赋值
            list.add(questions);
        }
        return list;
    }

    @Override
    public List<Questions> findByIdsForStu(String[] ids) {
        //String idss=ToolUtil.arraytoString(ids);
        List<Questions> list = new ArrayList<>();
        for (String id : ids) {
            if (id.equals("")) {
                continue;
            }
            //去除富文本编辑器添加的段首与段尾的<p>标签
            Questions questions = questionsMapper.selectByPrimaryKey(Integer.valueOf(id));
            int index = questions.getQuetitle().indexOf("<p>");
            if (index == 0) {
                questions.setQuetitle(questions.getQuetitle().substring(3, questions.getQuetitle().length() - 4));
            }
            int index1 = questions.getChoiced().indexOf("<p>");
            if (index1 == 0) {
                questions.setChoiced(questions.getChoiced().substring(3, questions.getChoiced().length() - 4));
            }
            int index2 = questions.getChoicec().indexOf("<p>");
            if (index2 == 0) {
                questions.setChoicec(questions.getChoicec().substring(3, questions.getChoicec().length() - 4));
            }
            int index3 = questions.getChoiceb().indexOf("<p>");
            if (index3 == 0) {
                questions.setChoiceb(questions.getChoiceb().substring(3, questions.getChoiceb().length() - 4));
            }
            int index4 = questions.getChoicea().indexOf("<p>");
            if (index4 == 0) {
                questions.setChoicea(questions.getChoicea().substring(3, questions.getChoicea().length() - 4));
            }
            //HtmlUtils重新赋值
            questions.setChoiced(HtmlUtils.htmlEscape(questions.getChoiced()));
            questions.setChoicec(HtmlUtils.htmlEscape(questions.getChoicec()));
            questions.setChoiceb(HtmlUtils.htmlEscape(questions.getChoiceb()));
            questions.setChoicea(HtmlUtils.htmlEscape(questions.getChoicea()));

            list.add(questions);
        }
        return list;
    }

    @Override
    public Questions findQuestionById(int id) {
        return null;
    }

    @Override
    public List<Questions> findQuestion(int courseId, int num) {
        return null;
    }

    @Override
    public List<BigQuestion> findQuestionByType(int courseId, int num, int tpye) {
        return null;
    }

    @Override
    public ServerResponse<PageInfo> showAllQuestions(String courseName,String questionTitle,int pageNum, int pageSize) {
        //获取分页信息
        PageHelper.startPage(pageNum, pageSize);
        //获取需要显示的所有试题
        List<QuestionVo> questionses = questionsMapper.showAllQuestions(courseName,questionTitle);

        //分页
        PageInfo pageInfo = new PageInfo(questionses);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public Page findPage(Page page) {
        return null;
    }

    @Override
    public Page findBigPage(Page page) {
        return null;
    }

    @Override
    public ServerResponse uploadQuestion(InputStream inputStream) throws Exception {
//        ExcelUtil excelUtil = new ExcelUtil(inputStream, "2007");
//        String[] propertyNames = {"EpName", "EnterId", "sName", "sId", "ClassName", "Phone", "Choice","Money", "Position", "TypeB", "TypeM", "State"};
//        Class<?>[] propertyTypes = {String.class, Integer.class, String.class, Integer.class, String.class, String.class, String.class,  String.class, String.class,Integer.class, Integer.class, Integer.class};
//        List<SignVo> signVos = excelUtil.readExcel(propertyNames, propertyTypes, SignVo.class);
//        for (SignVo signVo : signVos) {
//            Sign sign = new Sign();
//            sign.setEnterId(signVo.getEnterId());
//            sign.setsId(signVo.getsId());
//            sign.setTypeB(signVo.getTypeB());
//            sign.setTypeM(signVo.getTypeM());
//            sign.setState(signVo.getState());
//            int result = signMapper.updateByPrimaryKeySelective(sign);
//            if (result <= 0) {
//                return ServerResponse.createByErrorMsg("导入中途失败, 请重试");
//            }
//        }
//        return ServerResponse.createBySuccessMsg("导入成功");
        return null;
    }


    @Override
    public ServerResponse loadinExcel(InputStream inputStream, Integer courseId) throws Exception {
        ExcelUtil excelUtil = new ExcelUtil(inputStream, "2007");
        String[] propertyNames = {"Quetitle", "Choicea", "Choiceb", "Choicec", "Choiced", "Ans"};
        Class<?>[] propertyTypes = {String.class, String.class, String.class, String.class, String.class, String.class};
        List<Questions> questions = null;
        try {
            questions = excelUtil.readExcel(propertyNames, propertyTypes, Questions.class);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("您导入的excel有纯数字,请在前边加一个英文单引号或者给他后边加个空格");
        }
        for (Questions q : questions) {
            q.setQueexist(1);
            q.setQuetype(1);
            q.setCourseid(courseId);
            questionsMapper.insert(q);
        }
        return ServerResponse.createBySuccessMsg("导入成功");
    }

    public void outputSelectQuestionExcelTitle(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//        String[] title = {"题干","A选项","B选项","C选项","D选项","答案","(注意，请不要输入纯数字，如果需要则在数字前加入英文单引号，请在导入之前把这句话删掉)"};
        String[] title = {"题干", "A选项", "B选项", "C选项", "D选项", "答案"};
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("sheet1");
        XSSFRow row = sheet.createRow(0);
        XSSFCellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 10);
        style.setLocked(true);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setDataFormat(workbook.createDataFormat().getFormat("@"));
        style.setAlignment(HorizontalAlignment.CENTER);
        //添加单元格注释
        //创建HSSFPatriarch对象,HSSFPatriarch是所有注释的容器.
        XSSFDrawing patr = sheet.createDrawingPatriarch();
        //定义注释的大小和位置,详见文档
        XSSFComment comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
        //设置注释内容
        comment.setString(new XSSFRichTextString("注意，请在纯数字前加入英文单引号[']"));

        for (int i = 0; i < title.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[i]);
            cell.setCellType(CellType.STRING);
            cell.setCellComment(comment);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        workbook.close();
        new DownloadUtil().download(os, resp, req, "选择题表头.xlsx");
    }

    @Override
    public ServerResponse<Map<String, Object>> editQuestions(Questions questions) {
        Map<String, Object> returnMap = new HashMap<>();
        //获取这个题号的信息
        Questions question = questionsMapper.selectByPrimaryKey(questions.getId());
        //如果是修改该对象用于值的回显
        returnMap.put("question", question);
        List<Course> allCourse = courseMapper.getAllCourseOrderById();
        //获取所有的课程信息
        returnMap.put("allCourse", allCourse);
        if (question != null) {
            return ServerResponse.createBySuccess("修改", returnMap);
        } else {
            return ServerResponse.createBySuccess("添加", returnMap);
        }
    }

    @Override
    public ServerResponse updateQuestion(Questions question) {
        //判断是修改还是添加,如果id为空则是添加
        int result = -1;
        if (question.getId() == null) {
            //传过来的question的类型为Null,exist为null
            question.setQuetype(1);
            question.setQueexist(1);
            result = questionsMapper.insert(question);
            if (result == 1) {
                return ServerResponse.createBySuccess("添加成功");
            } else {
                return ServerResponse.createByErrorMsg("添加失败");
            }
        } else {
            result = questionsMapper.updateByPrimaryKeySelective(question);
            if (result == 1) {
                return ServerResponse.createBySuccess("修改成功");
            } else {
                return ServerResponse.createByErrorMsg("修改失败");
            }
        }
    }

    @Override
    public ServerResponse<Questions> deleteQuestion(Questions question) {
        question.setQueexist(0);
        int result = questionsMapper.updateByPrimaryKeySelective(question);
        if (result == 1) {
            return ServerResponse.createBySuccessMsg("删除成功");
        }
        return ServerResponse.createByErrorMsg("删除失败");
    }
}
